import axios from 'axios'
import Store from '@/modules/Store'

var instance = axios.create({
    baseURL:'/api',
    timeout:30000,
    headers:{
        'Accept':'application/json',
        'Content-type':'application/json'
    },
})


/**
 * 真正执行请求的函数
 */
function doRequest(url,method,config) {
    return instance.request({
        url:url,
        method:method,
        ...config
    });
}

//请求发送之前的拦截器
instance.interceptors.request.use(function(config){
    // 发送请求之前可以改变config内容或者阻止请求
    // console.log('interceptors.request');
    config.headers['Authorization'] = 'Bearer '+Store.state.user.token;
    return config;
},function(error){
    return Promise.reject(error);
});

//请求结果数据的拦截器
instance.interceptors.response.use(function(response){
    // 请求返回内容后,对请求返回的内容进行拦截修改
    console.log('interceptors.response');
    if(response.data.errcode > 0){
        $.message({
            message:response.data.message,
            type:'warning'
        });
        return Promise.reject(response);
    }
    return response;
},function(error){
    console.log(error.response.data);
    var data = error.response.data.message;
    if(data == undefined) {
        data = JSON.stringify(error.response.data);
    }

    $.message({
        message:'请求出错:'+data,
        type:'error'
    });

    // console.log('interceptors.response error');
    // console.dir(error);
    return Promise.reject(error);
});


export default {

    get(url,query,config) {
        if(query != undefined){
            if(config == undefined){
                config = {};
            }
            config.params = query;
        }
        return doRequest(url,'get',config);
    },

    post(url,data,config) {
        if(config == undefined){
            config = {};
        }
        config.data = data;
        return doRequest(url,'post',config);
    },

    put(url,data,config) {
        if(config == undefined){
            config = {};
        }
        config.data = data;
        return doRequest(url,'put',config);
    },

    delete(url,config) {
        return doRequest(url,'delete',config);
    }

}
